//
//  BCHomeAdsController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/12/26.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCHomeAdsController.h"
//
#import "BCHomeAdCollectionCell.h"


@interface BCHomeAdsController () <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic, assign) CGRect fromFrame;

/**
 *selectBlock
 */
@property (nonatomic, copy) BCHomeAdsControllerSelectBlock selectBlock;

#pragma mark - views

/**
 *adCollection
 */
@property (nonatomic, strong) UICollectionView *adCollection;

/**
 *adPageControl
 */
@property (nonatomic, strong) UIPageControl *adPageControl;

/**
 *closeButton
 */
@property (nonatomic, strong) QMUIButton *closeButton;

/**
 *dataSource
 */
@property (nonatomic, copy) NSArray <BCAdsDataModel *> *dataSource;

@end

@implementation BCHomeAdsController

+ (void)showFromController:(UIViewController *)fromController forFrame:(CGRect)fromFrame ads:(NSArray <BCAdsDataModel *> *)ads selectedAdModelBlock:(BCHomeAdsControllerSelectBlock)selectBlock {
    BControllerWindow *window = [[BControllerWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    window.windowLevel = UIWindowLevelAlert;
    BCHomeAdsController *vc = [BCHomeAdsController new];
    vc.showWindow = window;
    vc.fromFrame = fromFrame;
    vc.dataSource = ads;
    vc.selectBlock = selectBlock;
    window.rootViewController = vc;
    [window makeKeyAndVisible];
}

- (QMUIButton *)closeButton {
    if (!_closeButton) {
        UIImage *image = [LOAD_IMAGE(@"general_close") imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        _closeButton = [QMUIButton new];
        [_closeButton setImage:image forState:UIControlStateNormal];
        _closeButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        [_closeButton sizeToFit];
        [self.view addSubview:_closeButton];
        _closeButton.layer.cornerRadius = _closeButton.frame.size.height/2;
        _closeButton.tintColor = [UIColor whiteColor];
        _closeButton.backgroundColor = [UIColor colorWithWhite:0 alpha:.8];
        [_closeButton addTarget:self action:@selector(closeButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeButton;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
    //
    [self showContentView];
}
- (void)setupSubviews {
    [self.view addSubview:self.backgroundView];
    self.backgroundView.alpha = 0;
    [self.backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    //
    self.closeButton.alpha = 0;
    
    //
    [self.view addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(self.view).multipliedBy(.8);
        make.height.mas_equalTo(self.contentView.mas_width).multipliedBy(9.0/6);
        make.centerY.mas_equalTo(self.view).offset(-self.closeButton.frame.size.height);
    }];
    self.contentView.layer.cornerRadius = 10;
    self.contentView.layer.masksToBounds = true;
    
    [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.contentView.mas_bottom).offset(self.closeButton.frame.size.height);
    }];
    
    //
    [self setContents];
    //
    [self.view layoutIfNeeded];
}
- (void)setContents {
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsZero;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    self.adCollection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.adCollection.backgroundColor = [UIColor clearColor];
    self.adCollection.dataSource = self;
    self.adCollection.delegate = self;
    [self.contentView addSubview:self.adCollection];
    self.adCollection.pagingEnabled = true;
    self.adCollection.showsHorizontalScrollIndicator = false;
    self.adCollection.bounces = false;
    [self.adCollection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.contentView);
    }];
    //
    [self.adCollection registerClass:BCHomeAdCollectionCell.class forCellWithReuseIdentifier:NSStringFromClass(BCHomeAdCollectionCell.class)];
    
    //
    self.adPageControl = [UIPageControl new];
    [self.contentView addSubview:self.adPageControl];
    [self.adPageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.contentView);
        make.bottom.mas_equalTo(self.contentView).offset(-15.0);
    }];
    //
    self.adPageControl.numberOfPages = self.dataSource.count;
    self.adPageControl.currentPage = 0;
    self.adPageControl.alpha = self.dataSource.count==1?0:1;
    //
    self.adPageControl.currentPageIndicatorTintColor = [UIColor darkMainColor];
    self.adPageControl.pageIndicatorTintColor = [UIColor whiteColor];
}
//
- (void)showContentView {
    if (CGRectEqualToRect(CGRectZero, self.fromFrame)) {
        self.contentView.alpha = 0.5;
        self.contentView.transform = CGAffineTransformMakeScale(0, 0);
        [UIView animateWithDuration:0.25 animations:^{
            self.backgroundView.alpha = 0.16;
            self.contentView.alpha = 1;
            self.contentView.transform = CGAffineTransformMakeScale(1, 1);
        } completion:^(BOOL finished) {
            self.closeButton.alpha = 1;
        }];
    }else {
        UIImage *contentImage = [self.contentView qmui_snapshotLayerImage];
        UIImageView *animationIV = [[UIImageView alloc] initWithFrame:self.fromFrame];
        animationIV.image = contentImage;
        animationIV.layer.cornerRadius = self.contentView.layer.cornerRadius;
        animationIV.layer.masksToBounds = true;
        [self.view addSubview:animationIV];
        self.contentView.alpha = 0;
        //
        animationIV.alpha = 0;
        CGRect contentFrame = self.contentView.frame;
        [UIView animateWithDuration:.3 animations:^{
            animationIV.frame = contentFrame;
            self.backgroundView.alpha = 0.16;
            animationIV.alpha = 1;
        } completion:^(BOOL finished) {
            [animationIV removeFromSuperview];
            self.contentView.alpha = 1;
            [UIView animateWithDuration:.3 animations:^{
                self.closeButton.alpha = 1;
            }];
        }];
        
    }
}

#pragma mark - scroll
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    self.adPageControl.currentPage = scrollView.contentOffset.x/scrollView.frame.size.width;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.adPageControl.currentPage = scrollView.contentOffset.x/scrollView.frame.size.width;
}

#pragma mark - UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BCHomeAdCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(BCHomeAdCollectionCell.class) forIndexPath:indexPath];
    cell.cellSize = self.contentView.frame.size;
    cell.adModel = self.dataSource[indexPath.row];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(collectionView.qmui_width, collectionView.qmui_height);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    BCAdsDataModel *adModel = self.dataSource[indexPath.row];
    if (self.selectBlock) {
        self.selectBlock(adModel);
    }
    [self dismissWindow];
}


#pragma mark - closeButtonDidClickedAction
- (void)closeButtonDidClickedAction {
    [_closeButton removeFromSuperview];
    if (CGRectEqualToRect(CGRectZero, self.fromFrame)) {
        [UIView animateWithDuration:0.25 animations:^{
            self.backgroundView.alpha = 0.3;
            self.contentView.alpha = .5;
            self.contentView.transform = CGAffineTransformMakeScale(0, 0);
        } completion:^(BOOL finished) {
            [self dismissWindow];
        }];
    }else {
        UIImage *contentImage = [self.contentView qmui_snapshotLayerImage];
        self.contentView.alpha = 0;
        UIImageView *animationIV = [[UIImageView alloc] initWithFrame:self.contentView.frame];
        animationIV.image = contentImage;
        animationIV.layer.cornerRadius = self.contentView.layer.cornerRadius;
        animationIV.layer.masksToBounds = true;
        [self.view addSubview:animationIV];
        //
        [UIView animateWithDuration:.3 animations:^{
            animationIV.frame = self.fromFrame;
            self.backgroundView.alpha = 0;
            animationIV.alpha = 0;
        } completion:^(BOOL finished) {
            [animationIV removeFromSuperview];
            [self dismissWindow];
        }];
        
    }
}

@end
